package com.shishuo.cdn.action;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.util.AlipayNotify;
import com.shishuo.cdn.dao.UserBankLogDao;
import com.shishuo.cdn.dao.UserDao;
import com.shishuo.cdn.util.ConfigUtil;
import com.unionpay.acp.demo.BackRcvResponse;
import com.unionpay.acp.demo.DemoBase;
import com.unionpay.acp.demo.FrontRcvResponse;
import com.unionpay.acp.sdk.LogUtil;
import com.unionpay.acp.sdk.SDKConfig;
import com.unionpay.acp.sdk.SDKConstants;
import com.unionpay.acp.sdk.SDKUtil;
@Controller
@RequestMapping(value="/pay")
public class PayAction extends BaseAction {
	@Autowired
	private UserBankLogDao userBankLogDao;
	@Autowired
	private UserDao userDao;
	//加载银联配置
//	static{SDKConfig.getConfig().loadPropertiesFromSrc();}
	/**   
	* 描述： 发起支付宝支付
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年6月26日 上午9:35:23   
	* 修改备注：   
	* @version    
	*    
	*/ 
	@RequestMapping(value="/alipayapi.htm")
	public String toAliPayView(HttpServletRequest request){//,HttpServletResponse response
		createParameterMap(request);
//		System.out.println("-----------------------------------------------------------------------------------------------");
//		paramsMap.put("type", 1);//1:自己充值
		paramsMap.put("status",0);//0:未充值成功的订单
		paramsMap.put("pay_way",1);//1:支付宝
//		System.out.println(paramsMap);
		 List<Map<String,Object>>templist= userBankLogDao.queryuserBankLog(paramsMap);
//		 Collections.reverse(templist);
		 Map<String,Object> orderMap=templist.get(0);
//		 for(Map one:templist)
//		 {
////			 System.out.println("status:"+one.get("status")+"  type:"+one.get("type")+"    "+("0".equals(one.get("status").toString()) || "1".equals(one.get("type").toString())));
//			 if("0".equals(one.get("status").toString()) && paramsMap.get("bank_type").equals(one.get("type").toString()))
//			 {
//				 orderMap=one;
//				 break;
//			 }
//		 }
//		 Map<String,Object> orderMap=templist.get(0);
		 
		request.setAttribute("WIDout_trade_no", orderMap.get("order_sn"));//订单号
		request.setAttribute("WIDsubject",orderMap.get("description") );//订单名 orderMap.get("description")
		request.setAttribute("WIDtotal_fee", orderMap.get("bank_money"));//订单金额
		request.setAttribute("WIDbody", "");//订单描述
		request.setAttribute("WIDshow_url", ConfigUtil.getProjectHttpUrl()+"/myCdn/index_bus.htm");//商品地址
	return "/alipay/alipayapi";
	}
	/**   
	* 描述：   接收支付宝通知（后台）
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年6月30日 上午11:07:24   
	* 修改备注：   
	* @version    
	*    
	*/ 
	@ResponseBody
	@RequestMapping(value="/receiveAlipayBack.htm")
	public String receiveAlipayBack (HttpServletRequest request){
		
		System.out.println("enter receiveAlipayBack method--------------------------");
		System.out.println("enter receiveAlipayBack method--------------------------");
		System.out.println("enter receiveAlipayBack method--------------------------");
		System.out.println("enter receiveAlipayBack method--------------------------");
		System.out.println("enter receiveAlipayBack method--------------------------");
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			System.out.println("-==================================");
			System.out.println("-==================================");
			System.out.println("name:"+name+" value:"+values);
			System.out.println("-==================================");
			System.out.println("-==================================");
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no="";
		try {
			 out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//支付宝交易号
		String trade_no ="";
		try {
			 trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//交易状态
		String trade_status="";
		try {
			trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		//交易状态
		String buyer_email="";
		try {
			buyer_email = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		System.out.println("获取支付宝的通知返回参数------------------------》");
		System.out.println("获取支付宝的通知返回参数------------------------》");
		System.out.println("获取支付宝的通知返回参数------------------------》"+AlipayNotify.verify(params));
		System.out.println("获取支付宝的通知返回参数------------------------》");
		System.out.println("获取支付宝的通知返回参数------------------------》");
		if(AlipayNotify.verify(params)){//验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代码
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("order_sn", out_trade_no);
			map.put("status", 1);
			map.put("card_number",buyer_email );//付款者 自付宝帐号
			userBankLogDao.modifyUserBankLog(map);//刷新订单状态
			List<Map<String,Object>> listOrderMap= userBankLogDao.queryuserBankLog(map);
			if(listOrderMap!=null && listOrderMap.size()>0)
			{
				Map<String,Object> orderMap=listOrderMap.get(0);
				System.out.println("----------->");
				System.out.println("----------->");
				System.out.println("----------->");
				System.out.println(orderMap);
				System.out.println("----------->");
				System.out.println(orderMap.get("id"));
				System.out.println("----------->");
				System.out.println("----------->");
				paramsMap.clear();
				if("1".equals(orderMap.get("type").toString()))//给自己充值
				paramsMap.put("user_id",orderMap.get("user_id"));
				if("2".equals(orderMap.get("type").toString()))//给别人充值
				paramsMap.put("reg_tel",orderMap.get("to_user_id"));
				
				List<Map<String,Object>> listUserMap=userDao.queryUserByCondition(paramsMap);
				if(listUserMap!=null && listUserMap.get(0)!=null)
				{
					Map<String,Object> userMap=listUserMap.get(0);
				double newBalance =	(Double.valueOf(userMap.get("balance").toString())+Double.valueOf(orderMap.get("bank_money").toString()));
				paramsMap.put("balance",newBalance );
				
				System.out.println("----------->");
				System.out.println("----------->");
				System.out.println(paramsMap);
				System.out.println("----------->");
				System.out.println("----------->");
				userDao.modifyUserInfo(paramsMap);
				}

			}
			if(trade_status.equals("TRADE_FINISHED")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				System.out.println("------------------------》TRADE_FINISHED");
				System.out.println("------------------------》TRADE_FINISHED");
				System.out.println("------------------------》TRADE_FINISHED");
				System.out.println("------------------------》TRADE_FINISHED");
				System.out.println("------------------------》TRADE_FINISHED");
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
			} else if (trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
				System.out.println("------------------------》TRADE_SUCCESS");
				System.out.println("------------------------》TRADE_SUCCESS");
				System.out.println("------------------------》TRADE_SUCCESS");
				System.out.println("------------------------》TRADE_SUCCESS");
				System.out.println("------------------------》TRADE_SUCCESS");
				//注意：
				//付款完成后，支付宝系统发送该交易状态通知
			}

			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
			System.out.println("------------------------》success");
			System.out.println("------------------------》success");
			System.out.println("------------------------》success");
			System.out.println("------------------------》success");
			System.out.println("------------------------》success");
			return("success");	//请不要修改或删除

			//////////////////////////////////////////////////////////////////////////////////////////
		}else{//验证失败
			System.out.println("------------------------》fail");
			System.out.println("------------------------》fail");
			System.out.println("------------------------》fail");
			System.out.println("------------------------》fail");
			System.out.println("------------------------》fail");
			return("fail");
		}
	}
	
	/**   
	* 描述：   银联支付
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年6月30日 上午10:02:32   
	* 修改备注：   
	* @version    
	*    
	*/ 
	@ResponseBody
	@RequestMapping(value="/unionpay.htm")
	public String toUnionpayView(HttpServletRequest request,HttpServletResponse response){
		createParameterMap(request);
		paramsMap.put("status",0);//0:未充值成功的订单
		paramsMap.put("pay_way",2);//2:银联
		 List<Map<String,Object>>templist= userBankLogDao.queryuserBankLog(paramsMap);
		 Map<String,Object> orderMap=templist.get(0);
		
			request.setAttribute("WIDout_trade_no", orderMap.get("order_sn"));//订单号
			request.setAttribute("WIDsubject",orderMap.get("description") );//订单名 orderMap.get("description")
			request.setAttribute("WIDtotal_fee", orderMap.get("bank_money"));//订单金额
			request.setAttribute("WIDbody", "");//订单描述
			request.setAttribute("WIDshow_url", ConfigUtil.getProjectHttpUrl()+"/fund/fund.htm");//商品地址
		 
		SDKConfig.getConfig().loadPropertiesFromSrc();
		/**
		 * 组装请求报文
		 */
		Map<String, String> data = new HashMap<String, String>();
		// 版本号
		data.put("version", "5.0.0");
		// 字符集编码 默认"UTF-8"
		data.put("encoding", "UTF-8");
		// 签名方法 01 RSA
		data.put("signMethod", "01");
		// 交易类型 01-消费
		data.put("txnType", "01");
		// 交易子类型 01:自助消费 02:订购 03:分期付款
		data.put("txnSubType", "01");
		// 业务类型
		data.put("bizType", "000201");
		// 渠道类型，07-PC，08-手机
		data.put("channelType", "07");
		// 前台通知地址 ，控件接入方式无作用
//		data.put("frontUrl", "http://localhost:8080/ACPTest/acp_front_url.do");
		data.put("frontUrl",  ConfigUtil.getProjectHttpUrl()+"/pay/receiveUnionpayFront.htm");
//		data.put("frontUrl", "http://cchvc.nat123.net:24075/dotnet2/pay/receiveUnionpayFront.htm");
		// 后台通知地址
		data.put("backUrl", ConfigUtil.getProjectHttpUrl()+"/pay/receiveUnionpayBack.htm");
//		data.put("backUrl", "http://cchvc.nat123.net:24075/dotnet2/pay/receiveUnionpayBack.htm");
		
//		data.put("backUrl", "http://222.222.222.222:8080/ACPTest/acp_back_url.do");
		// 接入类型，商户接入填0 0- 商户 ， 1： 收单， 2：平台商户
		data.put("accessType", "0");
		// 商户号码，请改成自己的商户号
//		data.put("merId", "700000000000001");
//		data.put("merId", "777290058117365");
		data.put("merId", "898111448161398");
		// 商户订单号，8-40位数字字母
		data.put("orderId", orderMap.get("order_sn").toString().replaceAll("[\\D]", ""));//orderMap.get("order_sn").toString().replaceAll("[\\D]", "")
		// 订单发送时间，取系统时间
		data.put("txnTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
		// 交易金额，单位分
		System.out.println("-------------------------------"+String.valueOf(Double.valueOf(orderMap.get("bank_money").toString())*100));
		System.out.println("-------------------------------"+String.valueOf((int)(Double.valueOf(orderMap.get("bank_money").toString())*100)));
		System.out.println("-------------------------------"+String.valueOf(Double.valueOf(orderMap.get("bank_money").toString())*100));
		data.put("txnAmt", String.valueOf((int)(Double.valueOf(orderMap.get("bank_money").toString())*100)));
		// 交易币种
		data.put("currencyCode", "156");
		// 请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
//		 data.put("reqReserved", "透传信息");
		// 订单描述，可不上送，上送时控件中会显示该信息
//		 data.put("orderDesc", "订单描述");

		Map<String, String> submitFromData = DemoBase.signData(data);

		// 交易请求url 从配置文件读取
		String requestFrontUrl = SDKConfig.getConfig().getFrontRequestUrl();
		
		/**
		 * 创建表单
		 */
		String html = DemoBase.createHtml(requestFrontUrl, submitFromData);
		System.out.println(html);
		return html;
//		response.getWriter().write(html);
	}
	
	/**   
	* 描述：   银联返回(后台)
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年6月30日 上午10:17:46   
	* 修改备注：   
	* @version    
	*    
	*/ 
	@ResponseBody
	@RequestMapping(value="/receiveUnionpayBack.htm")
	public String receiveUnionpayBack(HttpServletRequest req,HttpServletResponse response){
		LogUtil.writeLog("BackRcvResponse接收后台通知开始");

		try {
			req.setCharacterEncoding("ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String encoding = req.getParameter(SDKConstants.param_encoding);
		// 获取请求参数中所有的信息
		Map<String, String> reqParam = BackRcvResponse.getAllRequestParam(req);
		System.out.println("------------------------------------------银联回调-----------------start");
		for(String key : reqParam.keySet()){
			System.out.println("-----------------------"+key+"--------------"+reqParam.get(key));
		}
		System.out.println("------------------------------------------银联回调-----------------end");
		// 打印请求报文
		LogUtil.printRequestLog(reqParam);

		Map<String, String> valideData = null;
		if (null != reqParam && !reqParam.isEmpty()) {
			Iterator<Entry<String, String>> it = reqParam.entrySet().iterator();
			valideData = new HashMap<String, String>(reqParam.size());
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				try {
					value = new String(value.getBytes("ISO-8859-1"), encoding);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				valideData.put(key, value);
			}
		}

		// 验证签名
//		if (!SDKUtil.validate(valideData, encoding)) {
//			LogUtil.writeLog("验证签名结果[失败].");
//			return"fail";
//		} else {
//			System.out.println("--银联回调-订单号："+valideData.get("orderId")); //其他字段也可用类似方式获取
//			LogUtil.writeLog("验证签名结果[成功].");
//		}
		System.out.println("--银联回调-订单号："+valideData.get("orderId")); //其他字段也可用类似方式获取
		LogUtil.writeLog("验证签名结果[成功].");

		LogUtil.writeLog("BackRcvResponse接收后台通知结束");
		Map<String,Object> map=new HashMap<String,Object>();
		String order_sn_temp=valideData.get("orderId");
		String order_sn=order_sn_temp.substring(0, 14)+"-"+order_sn_temp.substring(14,order_sn_temp.length());
		map.put("order_sn", order_sn);
		map.put("status", 1);
		map.put("card_number", valideData.get("accNo"));
		//map.put 付款帐号
		userBankLogDao.modifyUserBankLog(map);//刷新订单状态
		List<Map<String,Object>> listOrderMap= userBankLogDao.queryuserBankLog(map);
		if(listOrderMap!=null && listOrderMap.size()>0)
		{
			Map<String,Object> orderMap=listOrderMap.get(0);
			System.out.println("----------->");
			System.out.println(orderMap);
			System.out.println("----------->");
			System.out.println(orderMap.get("id"));
			System.out.println("----------->");
			paramsMap.clear();
			if("1".equals(orderMap.get("type").toString()))//给自己充值
			paramsMap.put("user_id",orderMap.get("user_id"));
			if("2".equals(orderMap.get("type").toString()))//给别人充值
			paramsMap.put("reg_tel",orderMap.get("to_user_id"));
			
			List<Map<String,Object>> listUserMap=userDao.queryUserByCondition(paramsMap);
			if(listUserMap!=null && listUserMap.get(0)!=null)
			{
				Map<String,Object> userMap=listUserMap.get(0);
			double newBalance =	(Double.valueOf(userMap.get("balance").toString())+Double.valueOf(orderMap.get("bank_money").toString()));
			paramsMap.put("balance",newBalance );
			
			System.out.println("----------->");
			System.out.println(paramsMap);
			System.out.println("----------->");
			userDao.modifyUserInfo(paramsMap);
			}
		}

		return"success";
	}
	
	/**   
	* 描述：   银联返回(前台)
	* 创建人：YangJ  邮箱:yangjie@sxw100.com   
	* 创建时间：2015年6月30日 上午10:55:53   
	* 修改备注：   
	* @version    
	*    
	*/ 
//	@ResponseBody
	@RequestMapping(value="/receiveUnionpayFront.htm")
	public String receiveUnionpayFront(HttpServletRequest req,HttpServletResponse resp){

		LogUtil.writeLog("FrontRcvResponse前台接收报文返回开始");

		try {
			req.setCharacterEncoding("ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String encoding = req.getParameter(SDKConstants.param_encoding);
		LogUtil.writeLog("返回报文中encoding=[" + encoding + "]");
		String pageResult = "";
		if ("UTF-8".equalsIgnoreCase(encoding)) {
			pageResult = "/utf8_result.jsp";
		} else {
			pageResult = "/gbk_result.jsp";
		}
		Map<String, String> respParam = FrontRcvResponse.getAllRequestParam(req);

		// 打印请求报文
		LogUtil.printRequestLog(respParam);

		Map<String, String> valideData = null;
		StringBuffer page = new StringBuffer();
		if (null != respParam && !respParam.isEmpty()) {
			Iterator<Entry<String, String>> it = respParam.entrySet()
					.iterator();
			valideData = new HashMap<String, String>(respParam.size());
			while (it.hasNext()) {
				Entry<String, String> e = it.next();
				String key = (String) e.getKey();
				String value = (String) e.getValue();
				try {
					value = new String(value.getBytes("ISO-8859-1"), encoding);
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				page.append("<tr><td width=\"30%\" align=\"right\">" + key
						+ "(" + key + ")</td><td>" + value + "</td></tr>");
				valideData.put(key, value);
			}
		}
//		if (!SDKUtil.validate(valideData, encoding)) {
//			page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>失败</td></tr>");
//			LogUtil.writeLog("验证签名结果[失败].");
//			req.setAttribute("flag", 0);
//		} else {
//			page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>成功</td></tr>");
//			LogUtil.writeLog("验证签名结果[成功].");
//			req.setAttribute("flag", 1);
//			System.out.println(valideData.get("orderId")); //其他字段也可用类似方式获取
//		}
		page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>成功</td></tr>");
		LogUtil.writeLog("验证签名结果[成功].");
		req.setAttribute("flag", 1);
		System.out.println(valideData.get("orderId")); //其他字段也可用类似方式获取
		
		req.setAttribute("result", page.toString());
//		req.getRequestDispatcher(pageResult).forward(req, resp);
		LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束");
		
		
		
		
		
		
		
		
		
		
		/*
		
		Map<String,Object> map=new HashMap<String,Object>();
		String order_sn_temp=valideData.get("orderId");
		String order_sn=order_sn_temp.substring(0, 14)+"-"+order_sn_temp.substring(14,order_sn_temp.length());
		map.put("order_sn", order_sn);
		map.put("status", 1);
		map.put("card_number", valideData.get("accNo"));
		//map.put 付款帐号
		userBankLogDao.modifyUserBankLog(map);//刷新订单状态
		List<Map<String,Object>> listOrderMap= userBankLogDao.queryuserBankLog(map);
		if(listOrderMap!=null && listOrderMap.size()>0)
		{
			Map<String,Object> orderMap=listOrderMap.get(0);
			System.out.println("----------->");
			System.out.println(orderMap);
			System.out.println("----------->");
			System.out.println(orderMap.get("id"));
			System.out.println("----------->");
			paramsMap.clear();
			if("1".equals(orderMap.get("type").toString()))//给自己充值
			paramsMap.put("user_id",orderMap.get("user_id"));
			if("2".equals(orderMap.get("type").toString()))//给别人充值
			paramsMap.put("reg_tel",orderMap.get("to_user_id"));
			
			List<Map<String,Object>> listUserMap=userDao.queryUserByCondition(paramsMap);
			if(listUserMap!=null && listUserMap.get(0)!=null)
			{
				Map<String,Object> userMap=listUserMap.get(0);
			double newBalance =	(Double.valueOf(userMap.get("balance").toString())+Double.valueOf(orderMap.get("bank_money").toString()));
			paramsMap.put("balance",newBalance );
			
			System.out.println("----------->");
			System.out.println(paramsMap);
			System.out.println("----------->");
			userDao.modifyUserInfo(paramsMap);
			}
		}
		
		*/
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		return "unionpay/utf8_result";
//		return page.toString();
	}
	
	
	
	
	
}
